import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt

# 读取数据
df = pd.read_excel('datas.xlsx', engine='openpyxl')  # 假设文件名为datas.xlsx

# 选择特征和目标变量
X = df[['正面信息', '负面信息', '中性信息', '拥堵指数', '物价指数']].values
y = df['承压指数'].values

# 数据标准化
scaler = MinMaxScaler()
X = scaler.fit_transform(X)

# 划分训练集和验证集
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)

# 构建DNN模型
model = Sequential()
model.add(Dense(256, input_dim=X.shape[1], activation='relu'))
model.add(Dense(128, activation='relu'))
model.add(Dense(64, activation='relu'))
model.add(Dense(1))  # 输出层，只有一个神经元，用于预测承压指数

# 编译模型
model.compile(loss='mean_squared_error', optimizer='adam')

# 训练模型并记录历史
history = model.fit(X_train, y_train, epochs=100, batch_size=16, verbose=1, validation_data=(X_val, y_val))

# 评估模型
loss = model.evaluate(X_val, y_val)
print('Validation loss:', loss)

# 保存模型到文件

model.save('my_model.h5')  # 这将保存整个模型到一个HDF5文件中